package com.arsn.myf.quartz.listener;

import com.arsn.myf.quartz.entity.ScheduledJob;
import com.arsn.myf.quartz.event.ScheduleEvent;
import com.arsn.myf.quartz.service.ScheduledJobService;
import com.arsn.myf.quartz.util.SpringBeanTaskUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 异步监听定时任务事件，解决job线程无故丢失的问题
 * @author zhongrj
 * @since 2022-03-10
 */
@Component
@AllArgsConstructor
@EnableAsync
@Slf4j
public class SchedulerListener {

    @Autowired
    private final ScheduledJobService scheduledJobService;

    @Async
    @EventListener(ScheduleEvent.class)
    public void scheduledJobListener(ScheduleEvent event){
        //获取事件对象
        ScheduledJob scheduledJob = event.getScheduledJob();
        log.info(scheduledJob.getName() + "开始执行......");
        //防止异步状态问题,不更新状态
        scheduledJob.setStatus(null);
        //执行时间
        scheduledJob.setActiveTime(new Date());
        //更新
        scheduledJobService.updateById(scheduledJob);
        //开始执行任务
        SpringBeanTaskUtil.invokeMethod(scheduledJob);
        log.info(scheduledJob.getName() + "任务执行结束......");
    }
}
